package servlet;

import util.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author LJ
 * @create 2022-04-21-16:00
 */
@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("name");
        System.out.println(username);
        String password = req.getParameter("password");
        System.out.println(password);
        try {
            Connection connection = DBUtils.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT username,`password` FROM `sys_user` WHERE username=? and `password`=? ");
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                Cookie cookie =new Cookie("username",username);
                Cookie cookie1 =new Cookie("password",password);
                resp.addCookie(cookie);
                resp.addCookie(cookie1);
                System.out.println("登陆成功");
                resp.sendRedirect("/TestServlet/goMain");
            }else {
                System.out.println("登陆失败");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}
